<template>
    <div class="customer-service">
        <button @click="toggleChat" :aria-expanded="centerDialogVisible.toString()">联系客服</button>
    </div>
    <div id="tippy-1" data-tippy-root>
        <el-dialog v-model="centerDialogVisible" title="客服小兔" width="600" align-center draggable>
            <div class="chat-area">
                <!-- 滑动对话区域 -->
                <div class="chat-container">
                    <!-- 显示结果 -->
                    <div class="connection-status">
                        {{ webSocketStore.message }}
                    </div>
                    <!-- 时间戳 -->
                    <div class="time">
                        {{ webSocketStore.time }}
                    </div>
                    <!-- 收到服务器消息显示 -->
                    <div class="user-message" v-for="(item, index) in webSocketStore.serverMessage" :key="index">
                        <div class="message" v-if="isEmoji(item)">
                            {{ item }}
                        </div>
                        <!-- 缩略图 -->
                        <div class="message" v-else-if="isImage(item)">
                            <img :key="index" id="image" :src="item" alt="" :class="{ zoomed: isZoomed }"
                                @click="openPreview(item, index)">
                        </div>
                        <!-- 文字消息 -->
                        <div class="message" v-else-if="isText(item)">
                            {{ item }}
                        </div>
                    </div>
                    <div>
                        <!-- 预览大图遮罩层 -->
                        <div class="overlay" :class="{ show: isPreviewOpen }" @click.self="closePreview">
                            <img :key="currentImageKey" v-if="isCurrentImage" :src="isCurrentImage" alt="预览图片"
                                class="preview-image">
                            <button class="close-button" @click="closePreview">✖</button>
                        </div>
                    </div>
                </div>
                <div class="chat-input-area">
                    <!-- 表情 -->
                    <div>
                        <V3EmojiPicker :theme="webSocketStore.theme" :recent="true" @click-emoji="addEmoji">
                        </V3EmojiPicker>
                    </div>
                    <!-- 图片 -->
                    <div class="image-upload">
                        <label for="fileInput" class="upload-label">
                            <!-- 自定义图标或者文本 -->
                            <svg t="1734016046391" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                xmlns="http://www.w3.org/2000/svg" p-id="1818" width="200" height="200">
                                <path
                                    d="M829.64898 849.502041H194.35102c-43.885714 0-79.412245-35.526531-79.412244-79.412245V253.910204c0-43.885714 35.526531-79.412245 79.412244-79.412245h635.29796c43.885714 0 79.412245 35.526531 79.412244 79.412245v516.179592c0 43.885714-35.526531 79.412245-79.412244 79.412245z"
                                    fill="#D2F4FF" p-id="1819"></path>
                                <path
                                    d="M909.061224 656.195918l-39.706122-48.065306L626.416327 365.714286c-19.330612-19.330612-50.677551-19.330612-70.008164 0L419.526531 502.073469c-2.612245 2.612245-5.22449 3.134694-6.791837 3.134694-1.567347 0-4.702041-0.522449-6.791837-3.134694L368.326531 464.979592c-19.330612-19.330612-50.677551-19.330612-70.008164 0l-143.673469 143.673469-39.706122 48.065306v113.893878c0 43.885714 35.526531 79.412245 79.412244 79.412245h635.29796c43.885714 0 79.412245-35.526531 79.412244-79.412245v-114.416327"
                                    fill="#16C4AF" p-id="1820"></path>
                                <path
                                    d="M273.763265 313.469388m-49.632653 0a49.632653 49.632653 0 1 0 99.265306 0 49.632653 49.632653 0 1 0-99.265306 0Z"
                                    fill="#E5404F" p-id="1821"></path>
                                <path
                                    d="M644.179592 768h-365.714286c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.897959h365.714286c11.493878 0 20.897959 9.404082 20.897959 20.897959s-9.404082 20.897959-20.897959 20.897959zM461.322449 670.82449h-182.857143c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.89796h182.857143c11.493878 0 20.897959 9.404082 20.897959 20.89796s-9.404082 20.897959-20.897959 20.897959z"
                                    fill="#0B9682" p-id="1822"></path>
                            </svg>
                            <input id="fileInput" type="file" accept="image/png" @change="webSocketStore.uploadImage"
                                class="file-input" @click="inputClick">
                        </label>
                    </div>
                </div>
                <!-- 用户输入框 -->
                <div class="chat-input">
                    <textarea id="textarea" class="el-input" type="text" v-model="userQuery" placeholder="输入您的问题">
                    </textarea>
                    <div id="imageContainer"></div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button aria-expanded="true" class="el-button" type="primary" @click="sendQuery">
                        发送
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import 'tippy.js/themes/light.css'
import { useWebSocketStore } from '@/stores/websocket'
import V3EmojiPicker from 'vue3-emoji'
import 'vue3-emoji/dist/style.css'
import { ref, onMounted } from 'vue';
const userQuery = ref('')
const centerDialogVisible = ref(false)
const isPreviewOpen = ref(null)
const AllEmoji = ref([])
//判断是不是当前图片
const isCurrentImage = ref(false)
const srcList = [
    'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
]
const isText = (item) => {
    // 使用正则表达式检查是否为纯文字，包括中文、英文和数字
    const chineseRegex = /[\u4e00-\u9fa5]/; // 中文字符范围
    return typeof item === 'string' && item.trim().length > 0 &&
        (/[a-zA-Z0-9\u4e00-\u9fa5.,?!]/.test(item) || chineseRegex.test(item));
}
//唯一的key值防止图片重复
const currentImageKey = ref(0)
//openPreview
const openPreview = (image, index) => {
    isCurrentImage.value = image;
    currentImageKey.value = index + new Date().getTime(); // 确保唯一 key
    isPreviewOpen.value = true;
}
//closePreview
const closePreview = () => {
    isPreviewOpen.value = false;
    setTimeout(() => {
        isCurrentImage.value = false;
    }, 1000)
}
//加载失败时候
const handleImageError = (event) => {
    console.log('图片加载失败：', event);
}
//图片放大
const isZoomed = ref(false)
const zoomImage = () => {
    isZoomed.value = !isZoomed.value
}
//联系客服
const toggleChat = () => {
    centerDialogVisible.value = !centerDialogVisible.value;
};
//实例化websocket store
const webSocketStore = useWebSocketStore();
//emoji选择器
const addEmoji = (emoji) => {
    //将emoji添加到AllEmoji
    // AllEmoji.value.push(emoji)
    userQuery.value += emoji // 添加选中的 Emoji 到输入框
    // console.log(AllEmoji.value);
};
//判断是不是图片
const isImage = (url) => {
    const img = new Image();
    img.src = url;
    return img.complete && img.naturalWidth !== 0;
}
//判断是否是emoji
const isEmoji = (character) => {
    // let strCharacter = String(character); // 转换为字符串
    // 判断 Unicode 范围
    const code = character.codePointAt(0);
    return (
        (code >= 0x1F600 && code <= 0x1F64F) || // 表情符号
        (code >= 0x1F300 && code <= 0x1F5FF) || // 其他符号
        (code >= 0x1F680 && code <= 0x1F6FF) || // 交通与地图符号
        (code >= 0x1F700 && code <= 0x1F77F) || // 其他符号
        (code >= 0x2700 && code <= 0x27BF)    // 特殊符号
    );
}
//发送信息逻辑
const sendQuery = () => {
    if (isEmoji(userQuery.value)) {
        webSocketStore.serverMessage.push(userQuery.value);// 添加消息到记录
        //发送给服务器
        webSocketStore.socket.send(userQuery.value);
    } else if (isText(userQuery.value)) {
        webSocketStore.serverMessage.push(userQuery.value);// 添加消息到记录
    } else {
        //提交imageContainer中的图片
        const images = document.querySelectorAll('#textarea img');
        for (let i = 0; i < images.length; i++) {
            webSocketStore.sendImage(images[i].src);
        }
    }
    // 清空 imageContainer
    document.getElementById('textarea').innerHTML = '';
    // 清空输入框
    userQuery.value = '';
};
onMounted(() => {
    // 监听主题切换
    webSocketStore.updateTheme()
    // 连接websocket
    webSocketStore.connect('ws://localhost:8080/ws')
});
</script>
<style scoped lang="scss">
.close-button {
    top: 20px;
    right: 20px;
    font-size: 24px;
    color: white;
    cursor: pointer;
    background: none;
    border: none;
    border-radius: 5px;
}

/* 遮罩层 */
.overlay {
    position: fixed;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s ease, visibility 0.3s ease;
}

.overlay.show {
    visibility: visible;
    opacity: 1;
}

/* 预览图片 */
.preview-image {
    max-width: 90vw;
    max-height: 90vh;
    box-shadow: 0 4px 15px rgba(255, 255, 255, 0.5);
}

.customer-service {
    display: flex;
    flex-direction: column;
    position: fixed;
    right: 0px;
    bottom: 300px;
    z-index: 1000;

    button {
        border: none;
        color: white;
        height: 50px;
        background-color: #27ba9b;
        font-size: 10px;
        white-space: nowrap;
        text-align: center;
        margin: 0 auto;
        border-radius: 5px;
        transition: background-color 0.3s;

        &:hover {
            background-color: #1e9e7a;
        }
    }
}

.chat-area {
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 500px;
    margin: 0;
    padding: 0;

    .chat-container {
        margin-bottom: 20px;
        padding: 0;
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow-y: scroll;

        div {
            height: 50px;
        }

        .server-message {
            font-size: 20px;
            text-align: left;
        }

        .connection-status {
            font-size: 12px;
            color: #888;
            text-align: center
        }

        .time {
            font-size: 12px;
            color: #888;
            text-align: center
        }

        .user-message {
            font-size: 20px;
            text-align: right;
        }

        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            max-width: 100%;
            clear: both;

            /* 避免浮动影响 */
            #image {
                cursor: pointer;
                object-fit: contain;
            }
        }

        .customer {
            background-color: #f1f1f1;
            text-align: right;
            margin-left: auto;
            /* 向右侧对齐 */
        }

        .support {
            background-color: #d1e7dd;
            text-align: left;
            margin-right: auto;
            /* 向左侧对齐 */
        }

        .chat-input {
            .el-input {
                padding: 0;
                margin: 0;
            }
        }
    }

    .image-upload {
        display: flex;
        align-items: center;
        position: relative;

        .upload-label {
            cursor: pointer;
            /* 绿色背景 */
            color: white;
            /* 内边距 */
            border-radius: 5px;
            /* 圆角 */
            transition: background-color 0.3s;

            /* 过渡效果 */
            .icon {
                position: absolute;
                top: 0;
                left: 20px;
                width: 30px;
                height: 30px;
            }
        }
    }

    .chat-input-area {
        display: flex;
        flex-direction: row;

        .file-input {
            display: none;
            /* 隐藏默认的文件输入 */
        }
    }
}

.dialog-footer {
    .el-button {
        background-color: #1e9e7a;
    }
}
</style>